package com.ncloud.resman.busi;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.DateUtils;
import com.ncloud.common.utils.excel.ExcelUtil;
import com.ncloud.resman.entity.Brand;
import com.ncloud.resman.entity.Cabinet;
import com.ncloud.resman.entity.DeviceBase;
import com.ncloud.resman.entity.DeviceIp;
import com.ncloud.resman.entity.DeviceLocation;
import com.ncloud.resman.entity.DeviceServer;
import com.ncloud.resman.entity.DeviceSub;
import com.ncloud.resman.entity.DeviceSwitch;
import com.ncloud.resman.entity.DeviceUnit;
import com.ncloud.resman.entity.ExportFire;
import com.ncloud.resman.entity.ExportServer;
import com.ncloud.resman.entity.ExportSwitchInfo;
import com.ncloud.resman.entity.Model;
import com.ncloud.resman.mapper.DictMapper;
import com.ncloud.resman.service.BrandService;
import com.ncloud.resman.service.CabinetService;
import com.ncloud.resman.service.DeviceBaseService;
import com.ncloud.resman.service.DeviceFirewallService;
import com.ncloud.resman.service.DeviceIpService;
import com.ncloud.resman.service.DeviceLocationService;
import com.ncloud.resman.service.DeviceServerService;
import com.ncloud.resman.service.DeviceSwitchService;
import com.ncloud.resman.service.DeviceSwitchSubService;
import com.ncloud.resman.service.DeviceUnitService;
import com.ncloud.resman.service.ModelService;

/**
 * user:sundelong  date:2017年8月24日
 */
@Service
public class DeviceExcelBusi {
	@Autowired
    private DeviceServerService deviceServerService;
    @Autowired
    private DeviceSwitchService deviceSwitchService;
    @Autowired
    private DeviceLocationService deviceLocationService;
    @Autowired
    private DeviceBaseService deviceBaseService;
    @Autowired
    private DeviceUnitService deviceUnitService;
    @Autowired
    private DeviceIpService deviceIpService;
    @Autowired
    private DeviceSwitchSubService deviceSwitchSubService;
    @Autowired
	private DictMapper dictMapper;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CabinetService cabinetServer;
    @Autowired
    private ModelService modelService;
    @Autowired
    private DeviceFirewallService deviceFirewallService;
	
	//导出服务器Excel
    public void exportServer(String snNum,HttpServletResponse response,boolean template) throws IOException{
    	if(snNum==""||snNum==null){
    		snNum=null;    		
    	}    	
    	List<ExportServer> listServers=new ArrayList<ExportServer>();
    	if(template){
    	
    		listServers=deviceServerService.getServerInfoBySnNum(snNum);
    	}
    	JSONArray listInfo = JSON.parseArray(JSON.toJSONString(listServers));
    	List<ExportServer> addListInfo=new ArrayList<ExportServer>();
    	
    	listInfo.stream().forEach(x -> {
    		ExportServer exportServer =new ExportServer();
    		exportServer = JSON.parseObject(JSON.toJSONString(x),ExportServer.class);
    		Long deviceId=exportServer.getDeviceId();
    		//加入IP
    		List<JSONObject> ipInfo=deviceIpService.getDeviceIpById(deviceId);
    		System.out.println(ipInfo.size());
    		for(JSONObject js:ipInfo){
    			String ip=js.get("ip").toString();
    			System.out.println(ip);
    			if(ip.indexOf("mgmt")!=-1){
    				exportServer.setiP1(ip);
    			}else if(ip.indexOf("service")!=-1){
    				exportServer.setiP2(ip);
    			}else if(ip.indexOf("public")!=-1){
    				exportServer.setiP3(ip);
    			}else{
    				exportServer.setiP4(ip);
    			}    			
    		}
    		//硬件信息
    		List<JSONObject> untiList=deviceUnitService.getDeviceUnitById(deviceId);
    		for(JSONObject js:untiList){
    			//brand_name
    			String unitType=js.get("unitType").toString();
    			String brandName=js.get("brandName").toString();
    			String capacity=js.get("capacity").toString();
    			String amount=js.get("amount").toString(); 
    			System.out.println(brandName);
    			System.out.println(unitType);
    			if(unitType.equals("1")){
    				System.out.println(brandName+"  "+capacity+"   "+amount);
    				exportServer.setcPUBrand(brandName);
    				exportServer.setcPUCapacity(capacity);
    				exportServer.setcPUAmount(amount);
    			}else if(unitType.equals("2")){
    				exportServer.setMemoryBrand(brandName);
    				exportServer.setMemoryCapacity(capacity);
    				exportServer.setMemoryAmount(amount);
    			}else if(unitType.equals("5")){
    				exportServer.setDiskBrand(brandName);
    				exportServer.setDiskCapacity(capacity);
    				exportServer.setDiskAmount(amount);
    			}else if(unitType.equals("3")){
    				exportServer.setnCardBrand(brandName);
    				exportServer.setnCardAmount(amount);
    			}
    		}
    		addListInfo.add(exportServer);            
        });
    	Date date=new Date();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMssHHddmm");
    	OutputStream os = null;
		String fileName = "服务器列表_"+(template?"模板":sdf.format(date))+".xls";
		response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
        os = response.getOutputStream();
		Map<String, String> map = new HashMap<String, String>();
        map.put("total", addListInfo.size()+" 条");
        map.put("date", DateUtils.getDate());
		ExcelUtil.getInstance().exportObj2ExcelByTemplate(map, "server-info-template.xls",os, addListInfo, ExportServer.class, true);
		
    	
    	System.out.print(addListInfo.size());
    }
    //导入服务器EXCEL
    public JSONObject importServer(InputStream inputStream,Object userID){
    	JSONObject json=new JSONObject();
    	List<Object> listInfo=ExcelUtil.getInstance().readExcel2ObjsByInputStream(inputStream, ExportServer.class);
    	if(listInfo==null||listInfo.size()==0){
			 json.put("info", "无数据插入");
			 return json;
		}
    	Long userId = null;

        if(userID!=null||userID!=""){
            userId = Long.parseLong(userID.toString());
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"userID 信息不存在");
        }
    	
    	for(int i=0;i<listInfo.size();i++){
    		ExportServer exportServer=(ExportServer)listInfo.get(i);
    		
    	if(exportServer.getSnNum()!=null&&exportServer.getSnNum()!=""){
    		DeviceBase deviceBase=new DeviceBase();
    		DeviceLocation deviceLocation=new DeviceLocation();
    		DeviceServer deviceServer=new DeviceServer();
    		DeviceUnit deviceUnit=new DeviceUnit();
    		DeviceIp deviceIp=new DeviceIp();
    		
    		String snNum=exportServer.getSnNum();
    		
    		Model model=modelService.getModelInfoByName(exportServer.getModelName());
    		
    		deviceBase.setModelName(exportServer.getModelName());
    		deviceBase.setModelId(model.getModelId());
    		deviceBase.setSnNum(exportServer.getSnNum());
    		deviceBase.setModelId(model.getModelId());
    		deviceBase.setBrandName(exportServer.getBrandName());
    		deviceBase.setBrandId(model.getBrandId());
    		deviceBase.setEqptType(model.getEqptType());
    		deviceBase.setTypeName(dictMapper.getDictValueByIdAndKey("eqpt_type", model.getEqptType()));
    		deviceBase.setEqptSpec(model.getEqptSpec());
    		deviceBase.setSpecName(exportServer.getSpecName());
    		deviceBase.setCreateUser(userId);
    		
    		deviceBase.setState(model.getState());
    		//deviceBase.setState(dictMapper.getDictKeyByIdAndValue("eqpt_state",exportServer.getState() ));
    		Long deviceId=0L;
    		int exists=deviceBaseService.existsDeviceBySnNum(snNum);
    		if(exists>0){
    			json.put(snNum,"设备"+snNum+" 已存在");
				continue;
    		}
    		deviceId=deviceBaseService.insertDeviceBase(deviceBase);
    		
    		deviceLocation.setDeviceId(deviceId);    		
    		Cabinet cabinet=cabinetServer.getRommIdByCabinetCode(exportServer.getCabinetCode());
    		deviceLocation.setSnNum(exportServer.getSnNum());
    		String cabinetId=cabinet.getCabinetId().toString();
    		int startNum=Integer.valueOf(exportServer.getStartNum());
    		int endNum=Integer.valueOf(exportServer.getEndNum());
    		deviceLocation.setRoomId(Long.parseLong(cabinet.getRoomId().toString()));
    		deviceLocation.setRoomName(exportServer.getRoomName());
    		deviceLocation.setCabinetId(Long.parseLong(cabinetId));
    		deviceLocation.setState(cabinet.getState().toString());
    		deviceLocation.setCabinetCode(exportServer.getCabinetCode());
    		deviceLocation.setStartNum(startNum);
    		deviceLocation.setEndNum(endNum);
    		deviceLocation.setCreateUser(userId);
    		//查询U位的使用情况 continue
    		String useState=null;
    		List<Integer> useList=new ArrayList<Integer>();
    		for(int k=startNum;k<=endNum;k++){
    			String uState=deviceLocationService.getCabinetUseState(cabinetId,String.valueOf(k));
    			if(uState==null){
    				json.put(snNum,"U位"+startNum+" 不存在");
    				deviceBaseService.deleteDeviceBase(deviceId);
    				continue;
    			}
    			if(uState.equals("1")){
    				useList.add(k);
    			}
    		}
    		if(useList.size()>0){
    			String info="设备 "+snNum+" 插入失败！"+" 机柜: "+exportServer.getCabinetCode()+" ID:"+cabinetId+" 的U位: "+useList.toString()+" 已被占用；";
    			json.put(snNum, info);
    			deviceBaseService.deleteDeviceBase(deviceId);
    			continue;
    		}else{
    			for(int k=startNum;k<=endNum;k++){
        			deviceLocationService.updateCabinetUse(deviceId, cabinetId,String.valueOf(k));
        		}
    		}
    		
    		deviceLocationService.insertLocation(deviceLocation);

    		deviceServer.setDeviceId(deviceId);
    		deviceServer.setPurpose(exportServer.getPurpose());
    		deviceServer.setIpmiAddr(exportServer.getIpmiAddr());
    		deviceServer.setManageIp(exportServer.getManageIp());
    		deviceServer.setSysModel(exportServer.getSysModel());
    		deviceServer.setServiceCode(exportServer.getServiceCode());
    		deviceServer.setHostName(exportServer.getHostName());
    		deviceServer.setCreateUser(userId);
    		deviceServerService.insertDeviceServer(deviceServer);
    		
    		String brandName=null;
    		deviceUnit.setDeviceId(deviceId);
    		//insert cpu unit_type1:CPU 2:内存 3:电源  4:网卡 5:硬盘
    		brandName=exportServer.getcPUBrand();
    		deviceUnit.setId(null);
    		Brand brand1=brandService.getBrandByEqptTypeAndBrandName("6",brandName);    
    		if(brand1==null||brand1.getBrandId()==null){
    			json.put(snNum+" "+brandName, brandName+"没有该品牌");
    		}else{
    		deviceUnit.setUnitType("1");
    		deviceUnit.setTypeName("CPU品牌");
    		deviceUnit.setBrandId(brand1.getBrandId());
    		deviceUnit.setBrandName(exportServer.getcPUBrand());
    		deviceUnit.setCapacity(exportServer.getcPUCapacity());
    		deviceUnit.setAmount(Integer.valueOf(exportServer.getcPUAmount()));		
    		deviceUnitService.insertDeviceUnit(deviceUnit);
    		}
    		
    		//insert 内存
    		deviceUnit.setId(null);
    		brandName=exportServer.getMemoryBrand();
    		Brand brand2=brandService.getBrandByEqptTypeAndBrandName("7",brandName);
    		if(brand2==null||brand2.getBrandId()==null){
    			json.put(snNum+" "+brandName, brandName+"没有该品牌");
    		}else{
    		deviceUnit.setUnitType("2");
    		deviceUnit.setTypeName("内存品牌");
    		deviceUnit.setBrandId(brand2.getBrandId());
    		deviceUnit.setBrandName(exportServer.getMemoryBrand());
    		deviceUnit.setCapacity(exportServer.getMemoryCapacity());
    		deviceUnit.setAmount(Integer.valueOf(exportServer.getMemoryAmount()));
    		deviceUnitService.insertDeviceUnit(deviceUnit);
    		}
    		//insert 网卡
    		brandName=exportServer.getnCardBrand();
    		deviceUnit.setId(null);
    		Brand brand3=brandService.getBrandByEqptTypeAndBrandName("10",brandName);
    		if(brand3==null||brand3.getBrandId()==null){
    			json.put(snNum+" "+brandName, brandName+"没有该品牌");
    		}else{
    		deviceUnit.setUnitType("4");
    		deviceUnit.setTypeName("网卡品牌");
    		deviceUnit.setBrandId(brand3.getBrandId());
    		deviceUnit.setBrandName(brandName);
    		deviceUnit.setCapacity("");
    		deviceUnit.setAmount(Integer.valueOf(exportServer.getnCardAmount()));
    		deviceUnitService.insertDeviceUnit(deviceUnit);
    		}
    		
    		//insert 硬盘
    		brandName=exportServer.getDiskBrand();
    		deviceUnit.setId(null);
    		Brand brand4=brandService.getBrandByEqptTypeAndBrandName("8",brandName);
    		if(brand4==null||brand4.getBrandId()==null){
    			json.put(snNum+" "+brandName, brandName+"没有该品牌");
    		}else{
    		deviceUnit.setUnitType("5");
    		deviceUnit.setTypeName("硬盘品牌");
    		deviceUnit.setBrandId(brand4.getBrandId());
    		deviceUnit.setBrandName(brandName);
    		deviceUnit.setCapacity(exportServer.getDiskCapacity());
    		deviceUnit.setAmount(Integer.valueOf(exportServer.getDiskAmount()));
    		deviceUnitService.insertDeviceUnit(deviceUnit);
    		}
    		
    		//ip1
    		if(exportServer.getiP4()!=null&&!exportServer.getiP1().isEmpty()){
    		deviceIp.setId(null);
    		deviceIp.setDeviceId(deviceId);
    		deviceIp.setIp(exportServer.getiP1());
    		deviceIpService.insertDeviceIp(deviceIp);
    		}
    		//ip2
    		if(exportServer.getiP4()!=null&&!exportServer.getiP2().isEmpty()){
    		deviceIp.setId(null);
    		deviceIp.setDeviceId(deviceId);
    		deviceIp.setIp(exportServer.getiP2());
    		deviceIpService.insertDeviceIp(deviceIp);
    		}
    		//ip3
    		if(exportServer.getiP4()!=null&&!exportServer.getiP3().isEmpty()){
    		deviceIp.setId(null);
    		deviceIp.setDeviceId(deviceId);
    		deviceIp.setIp(exportServer.getiP3());
    		deviceIpService.insertDeviceIp(deviceIp);
    		}
    		//ip4
    		if(exportServer.getiP4()!=null&&!exportServer.getiP4().isEmpty()){
    		deviceIp.setId(null);
    		deviceIp.setDeviceId(deviceId);
    		deviceIp.setIp(exportServer.getiP4());
    		deviceIpService.insertDeviceIp(deviceIp);
    		}
    		}
    	}
    	json.put("info","sucess");
		return json;
    }
    
  //导出交换机Excel
    public void exportSwitchInfos(String snNum,HttpServletResponse response,boolean template) throws IOException{
    	if(snNum==""||snNum==null){
    		snNum=null;    		
    	}    	
    	List<ExportSwitchInfo> swithInfos=new ArrayList<ExportSwitchInfo>();
    	if(template){
    	
    		swithInfos=deviceSwitchService.exportSwitchInfos(snNum);
    	}
    	JSONArray listInfo = JSON.parseArray(JSON.toJSONString(swithInfos));
 
    	Date date=new Date();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMssHHddmm");
    	OutputStream os = null;
		String fileName = "交换机列表_"+(template?"模板":sdf.format(date))+".xls";
		response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
        os = response.getOutputStream();
		Map<String, String> map = new HashMap<String, String>();
        map.put("total", swithInfos.size()+" 条");
        map.put("date", DateUtils.getDate());
		ExcelUtil.getInstance().exportObj2ExcelByTemplate(map, "swith-info-template.xls",os, listInfo, ExportSwitchInfo.class, true);
		   	
    }
    //导出交换机接口Excel
    public void exportSwitchSub(Long deviceId,HttpServletResponse response,boolean template) throws IOException{
	
    	List<DeviceSub> swithInfos=new ArrayList<DeviceSub>();
    	if(template){
    		swithInfos=deviceSwitchSubService.exportDeviceSwitchSub(deviceId);
    	}
    	JSONArray listInfo = JSON.parseArray(JSON.toJSONString(swithInfos));
 
    	Date date=new Date();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMssHHddmm");
    	OutputStream os = null;
		String fileName = "交换机接口列表_"+(template?"模板":sdf.format(date))+".xls";
		response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
        os = response.getOutputStream();
		Map<String, String> map = new HashMap<String, String>();
        map.put("total", listInfo.size()+" 条");
        map.put("date", DateUtils.getDate());
		ExcelUtil.getInstance().exportObj2ExcelByTemplate(map, "swithsub-info-template.xls",os, listInfo, DeviceSub.class, true);
		   	
    }
  //导入交换机infoEXCEL
    public JSONObject importSwitchInfo(InputStream inputStream,Object userID){
    	JSONObject json=new JSONObject();
    	List<Object> listInfo=ExcelUtil.getInstance().readExcel2ObjsByInputStream(inputStream, ExportSwitchInfo.class);
    	if(listInfo==null||listInfo.size()==0){
			 json.put("info", "无数据插入");
			 return json;
		}
    	Long userId = null;

        if(userID!=null||userID!=""){
            userId = Long.parseLong(userID.toString());
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"userID 信息不存在");
        }
    	
    	
    	for(int i=0;i<listInfo.size();i++){
    		ExportSwitchInfo exportSwitchInfo=(ExportSwitchInfo)listInfo.get(i);
    	if(exportSwitchInfo.getSnNum()!=null&&exportSwitchInfo.getSnNum()!=""){
    		DeviceBase deviceBase=new DeviceBase();
    		DeviceLocation deviceLocation=new DeviceLocation();
    		DeviceSwitch deviceSwitch=new DeviceSwitch();
    		DeviceUnit deviceUnit=new DeviceUnit();
    		
    		String snNum=exportSwitchInfo.getSnNum();
    		//传入base表
    		Model model=modelService.getModelInfoByName(exportSwitchInfo.getModelName());
    		
    		deviceBase.setModelName(exportSwitchInfo.getModelName());
    		deviceBase.setModelId(model.getModelId());
    		deviceBase.setSnNum(exportSwitchInfo.getSnNum());
    		deviceBase.setBrandName(exportSwitchInfo.getBrandName());
    		deviceBase.setBrandId(model.getBrandId());
    		deviceBase.setEqptType(model.getEqptType());
    		deviceBase.setTypeName(dictMapper.getDictValueByIdAndKey("eqpt_type", model.getEqptType()));
    		deviceBase.setEqptSpec(exportSwitchInfo.getEqptSpec());    		
    		deviceBase.setState(dictMapper.getDictKeyByIdAndValue("eqpt_state", exportSwitchInfo.getState())); 
    		deviceBase.setCreateUser(userId);
    		Long deviceId=0L;
    		int exists=deviceBaseService.existsDeviceBySnNum(snNum);
    		if(exists>0){
    			json.put(snNum,"设备"+snNum+" 已存在");
    			
				continue;
    		}
    		deviceId=deviceBaseService.insertDeviceBase(deviceBase);
    		//插入位置
    		deviceLocation.setDeviceId(deviceId);    		
    		Cabinet cabinet=cabinetServer.getRommIdByCabinetCode(exportSwitchInfo.getCabinetCode());
    		deviceLocation.setSnNum(exportSwitchInfo.getSnNum());
    		String cabinetId=cabinet.getCabinetId().toString();
    		int startNum=Integer.valueOf(exportSwitchInfo.getStartNum());
    		int endNum=Integer.valueOf(exportSwitchInfo.getEndNum());
    		deviceLocation.setRoomId(Long.parseLong(cabinet.getRoomId().toString()));
    		deviceLocation.setRoomName(exportSwitchInfo.getRoomName());
    		deviceLocation.setCabinetId(Long.parseLong(cabinetId));
    		deviceLocation.setState(cabinet.getState().toString());
    		deviceLocation.setCabinetCode(exportSwitchInfo.getCabinetCode());
    		deviceLocation.setStartNum(startNum);
    		deviceLocation.setEndNum(endNum);
    		deviceLocation.setCreateUser(userId);
    		//查询U位的使用情况 continue
    		String useState=null;
    		List<Integer> useList=new ArrayList<Integer>();
    		for(int k=startNum;k<=endNum;k++){
    			String uState=deviceLocationService.getCabinetUseState(cabinetId,String.valueOf(k));
    			if(uState==null){
    				json.put(snNum,"U位"+startNum+" 不存在");
    				deviceBaseService.deleteDeviceBase(deviceId);
    				continue;
    			}
    			if(uState.equals("1")){
    				useList.add(k);
    			}
    		}
    		if(useList.size()>0){
    			String info="设备 "+snNum+" 插入失败！"+" 机柜: "+exportSwitchInfo.getCabinetCode()+" ID:"+cabinetId+" 的U位: "+useList.toString()+" 已被占用；";
    			json.put(snNum, info);
    			deviceBaseService.deleteDeviceBase(deviceId);
    			continue;
    		}else{
    			for(int k=startNum;k<=endNum;k++){
        			deviceLocationService.updateCabinetUse(deviceId, cabinetId,String.valueOf(k));
        		}
    		}
    		
    		deviceLocationService.insertLocation(deviceLocation);
    		
    		//插入交换机表  
    		deviceSwitch.setDeviceId(deviceId);
    		deviceSwitch.setInterfaceNum(Integer.parseInt(exportSwitchInfo.getInterfaceNum()));
    		deviceSwitch.setG40Num(Integer.parseInt(exportSwitchInfo.getG40Num()));
    		deviceSwitch.setModuleNum(Integer.parseInt(exportSwitchInfo.getModuleNum()));
    		deviceSwitch.setPurpose(exportSwitchInfo.getPurpose());
    		deviceSwitch.setManageIp(exportSwitchInfo.getManageIp());
    		deviceSwitch.setHostName(exportSwitchInfo.getHostName());
    		deviceSwitch.setCreateUser(userId);
    		createInterface(deviceId, exportSwitchInfo.getInterfaceNum(), exportSwitchInfo.getG40Num(),userId);
    		deviceSwitchService.insertDeviceSwitch(deviceSwitch);	
    	}
    	}
    	json.put("info","sucess");
		return json;
    }
    //创建接口
    public void createInterface(Long deviceId,Object interfaceNum,Object g40Num,Long userId){
    	int faceNum=Integer.parseInt(interfaceNum.toString());
    	int gNum=Integer.parseInt(g40Num.toString());
    	int n=1;
    		for(int i=1;i<=faceNum;i++){
    			DeviceSub deviceSub=new DeviceSub();
    			deviceSub.setSubId(null);
        		deviceSub.setDeviceId(deviceId);
        		deviceSub.setSubType("1");		//普通接口
        		deviceSub.setState("1");		//UP
        		deviceSub.setSubNo(i);
        		deviceSub.setCreateUser(userId);
        		deviceSwitchSubService.insertDeviceSubSwitch(deviceSub);
        		n++;
    		}
    		int k=n;
    		for(int i=k;i<=k+gNum;i++){
    			DeviceSub deviceSub=new DeviceSub();
    			deviceSub.setSubId(null);
        		deviceSub.setDeviceId(deviceId);
        		deviceSub.setSubType("2");		//G40接口
        		deviceSub.setState("1");		//UP
        		deviceSub.setSubNo(i);
        		deviceSub.setCreateUser(userId);
        		deviceSwitchSubService.insertDeviceSubSwitch(deviceSub);
        		n++;
    		}
    		DeviceSub deviceSub=new DeviceSub();
			deviceSub.setSubId(null);
    		deviceSub.setDeviceId(deviceId);
    		deviceSub.setSubType("3");		//管理接口
    		deviceSub.setState("1");		//UP
    		deviceSub.setSubNo(n);
    		deviceSub.setCreateUser(userId);
    		deviceSwitchSubService.insertDeviceSubSwitch(deviceSub);   		

    }
    
  //导入交换机接口EXCEL
    public JSONObject importSwitchSubInfo(InputStream inputStream,Long deviceId,Long userId){
    	JSONObject json=new JSONObject();
    	List<Object> listInfo=ExcelUtil.getInstance().readExcel2ObjsByInputStream(inputStream, DeviceSub.class);
    	if(listInfo==null||listInfo.size()==0){
			 json.put("info", "无数据插入");
			 return json;
		}
    	
    	
    	for(int i=0;i<listInfo.size();i++){
    		
    		DeviceSub deviceSub=(DeviceSub)listInfo.get(i);
    	if(deviceSub.getSubNo()!=null){	
    		
    		String snNum=deviceSub.getSnNum();
    		//得到device_id
    		//Long deviceId=deviceBaseService.getDeviceIdBySnNum(snNum);
    		//不要插入suId
    		//deviceSub.setSubId(null);
    		deviceSub.setDeviceId(deviceId);
    		deviceSub.setUpdateUser(userId);
    		deviceSub.setSubType(dictMapper.getDictKeyByIdAndValue("sub_type",deviceSub.getSubType()));
    		deviceSub.setState(dictMapper.getDictKeyByIdAndValue("sub_state",deviceSub.getState()));
    		deviceSwitchSubService.updateSwitchSubSubNoInfo(deviceSub);
    	}
    	}
    	json.put("info","sucess");
		return json;
    }
    
  //导出防火墙Excel
    public void exportFireInfos(String snNum,HttpServletResponse response,boolean template) throws IOException{
    	if(snNum==""||snNum==null){
    		snNum=null;    		
    	}    	
    	List<ExportFire> fireInfos=new ArrayList<ExportFire>();
    	if(template){
    		fireInfos=deviceFirewallService.getFireInfoBySnNum(snNum);
    	}
    	JSONArray listInfo = JSON.parseArray(JSON.toJSONString(fireInfos));
 
    	Date date=new Date();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMssHHddmm");
    	OutputStream os = null;
		String fileName = "防火墙列表_"+(template?"模板":sdf.format(date))+".xls";
		response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
        os = response.getOutputStream();
		Map<String, String> map = new HashMap<String, String>();
        map.put("total", fireInfos.size()+" 条");
        map.put("date", DateUtils.getDate());
		ExcelUtil.getInstance().exportObj2ExcelByTemplate(map, "fire-info-template.xls",os, listInfo, ExportFire.class, true);
		   	
    }
  //导入防火墙infoEXCEL
    public JSONObject importFireInfo(InputStream inputStream,Object userID){
    	JSONObject json=new JSONObject();
    	List<Object> listInfo=ExcelUtil.getInstance().readExcel2ObjsByInputStream(inputStream, ExportFire.class);
    	if(listInfo==null||listInfo.size()==0){
			 json.put("info", "无数据插入");
			 return json;
		}
    	Long userId = null;
        if(userID!=null||userID!=""){
            userId = Long.parseLong(userID.toString());
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"userID 信息不存在");
        }
    	for(int i=0;i<listInfo.size();i++){
    		ExportFire exportFire=(ExportFire)listInfo.get(i);
    		if(exportFire.getSnNum()!=null&&exportFire.getSnNum()!=""){
    		DeviceBase deviceBase=new DeviceBase();
    		DeviceLocation deviceLocation=new DeviceLocation();
    		
    		String snNum=exportFire.getSnNum();
    		//传入base表
    		Model model=modelService.getModelInfoByName(exportFire.getModelName());
    		
    		deviceBase.setModelName(exportFire.getModelName());
    		deviceBase.setModelId(model.getModelId());
    		deviceBase.setSnNum(exportFire.getSnNum());
    		deviceBase.setBrandName(exportFire.getBrandName());
    		deviceBase.setBrandId(model.getBrandId());
    		deviceBase.setEqptType(model.getEqptType());
    		deviceBase.setTypeName(dictMapper.getDictValueByIdAndKey("eqpt_type", model.getEqptType()));
    		deviceBase.setEqptSpec(exportFire.getEqptSpec());
    		deviceBase.setCreateUser(userId);

    		deviceBase.setState(dictMapper.getDictKeyByIdAndValue("eqpt_state", exportFire.getState())); 
    		Long deviceId=0L;
    		int exists=deviceBaseService.existsDeviceBySnNum(snNum);
    		if(exists>0){
    			json.put(snNum,"设备"+snNum+" 已存在");
				continue;
    		}
    		deviceId=deviceBaseService.insertDeviceBase(deviceBase);
    		//插入位置
    		deviceLocation.setDeviceId(deviceId);    		
    		Cabinet cabinet=cabinetServer.getRommIdByCabinetCode(exportFire.getCabinetCode());
    		deviceLocation.setSnNum(exportFire.getSnNum());
    		String cabinetId=cabinet.getCabinetId().toString();
    		int startNum=Integer.valueOf(exportFire.getStartNum());
    		int endNum=Integer.valueOf(exportFire.getEndNum());
    		deviceLocation.setRoomId(Long.parseLong(cabinet.getRoomId().toString()));
    		deviceLocation.setRoomName(exportFire.getRoomName());
    		deviceLocation.setCabinetId(Long.parseLong(cabinetId));
    		deviceLocation.setState(cabinet.getState().toString());
    		deviceLocation.setCabinetCode(exportFire.getCabinetCode());
    		deviceLocation.setStartNum(startNum);
    		deviceLocation.setEndNum(endNum);
    		deviceLocation.setCreateUser(userId);
    		//查询U位的使用情况 continue
    		String useState=null;
    		List<Integer> useList=new ArrayList<Integer>();
    		for(int k=startNum;k<=endNum;k++){
    			String uState=deviceLocationService.getCabinetUseState(cabinetId,String.valueOf(k));
    			if(uState==null){
    				json.put(snNum,"U位"+startNum+" 不存在");
    				deviceBaseService.deleteDeviceBase(deviceId);
    				continue;
    			}
    			if(uState.equals("1")){
    				useList.add(k);
    			}
    		}
    		if(useList.size()>0){
    			String info="设备 "+snNum+" 插入失败！"+" 机柜: "+exportFire.getCabinetCode()+" ID:"+cabinetId+" 的U位: "+useList.toString()+" 已被占用；";
    			json.put(snNum, info);
    			deviceBaseService.deleteDeviceBase(deviceId);
    			continue;
    		}else{
    			for(int k=startNum;k<=endNum;k++){
        			deviceLocationService.updateCabinetUse(deviceId, cabinetId,String.valueOf(k));
        		}
    		}
    		
    		deviceLocationService.insertLocation(deviceLocation);
    		
    		//插入server  
    		DeviceServer deviceServer = new DeviceServer();
            deviceServer.setDeviceId(deviceId);
            deviceServer.setCreateUser(userId);
            deviceServerService.insertDeviceServer(deviceServer);	
    	}
    	}
    	json.put("info","sucess");
		return json;
    }
}
